package com.meituan.verintreport.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = {"com.meituan.verintreport.db.dao"}, sqlSessionFactoryRef = "sqlSessionFactoryReport")
public class MybatisReportDBConfig {

    @Autowired
    @Qualifier("reportDataSource")
    private DataSource reportDataSource;

    @Bean
    @Primary
    public SqlSessionFactory sqlSessionFactoryReport() throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(reportDataSource);
        factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().
                getResources("classpath*:mybatis-mapper/mysql/*.xml"));

        return factoryBean.getObject();
    }

    @Bean
    @Primary
    public SqlSessionTemplate sqlSessionTemplateReport() throws Exception {
        SqlSessionTemplate template = new SqlSessionTemplate(sqlSessionFactoryReport());
        return template;
    }
}
